<template>
  <div class="container">
    <div ref="toolbarRef" class="editor-toolbar"></div>
    <div ref="boxRef" class="editor-core" style="height: 400px; overflow-y: hidden"></div>
    <!-- <div style="margin-top: 20px; display: flex">
      <div style="flex: 1; padding-right: 5px">
        <textarea id="text-html" style="width: 100%; height: 300px" v-model="text_html"></textarea>
      </div>
      <div style="flex: 1; padding-left: 5px">
        <textarea id="text-json" style="width: 100%; height: 300px" v-model="text_json"></textarea>
      </div>
    </div> -->
  </div>
</template>
<script setup lang="ts">
// import type { IWangEditorP } from "../index";
import "@wangeditor/editor/dist/css/style.css";
import { type IDomEditor, createEditor, createToolbar, Boot } from "@wangeditor/editor";
import titleStyle from "@/components/HfwangEditor/plugins/titleStyle/index";
import quote from "@/components/HfwangEditor/plugins/quote/index";
// let props = withDefaults(defineProps<IWangEditorP>(), {});
const emit = defineEmits(["emitGetEditorValue"]);
const boxRef = ref(null);
const editorRef = shallowRef<IDomEditor>();
const toolbarRef = shallowRef();
const text_html = ref("");
const text_json = ref("");
const editorConfig = {
  onChange(editor: IDomEditor) {
    const html = editor.getHtml();
    text_html.value = html;
    const contentStr = JSON.stringify(editor.children, null, 2);
    text_json.value = contentStr;
    emit("emitGetEditorValue", html);
  }
};
function initEditor() {
  if (!boxRef.value) return;
  const toolbarConfig: toolbarConfigType = { insertKeys: { index: 26, keys: [] } };
  if (Boot.plugins.length == 12) {
    titleStyle(toolbarConfig);
    quote(toolbarConfig);
  }
  editorRef.value = createEditor({
    selector: boxRef.value as Element,
    html: "",
    config: editorConfig,
    mode: "default"
  });
  createToolbar({
    editor: editorRef.value,
    selector: toolbarRef.value as Element,
    config: toolbarConfig,
    mode: "default"
  });
}
function setHtml(e: string) {
  if (!editorRef.value) return;
  editorRef.value.setHtml(e);
}
function getHtml() {
  if (!editorRef.value) return;
  return editorRef.value.getHtml();
}
onMounted(() => {
  initEditor();
});
onUnmounted(() => {
  editorRef.value?.destroy();
});
defineExpose({ editorRef, setHtml, getHtml });
</script>

<style lang="scss" scoped>
.editor-core {
  border: 1px solid #d6d1d1;
  border-radius: 0px 0px 5px 5px;
}
.editor-toolbar {
  border-color: #d6d1d1;
  border-style: solid;
  border-width: 1px 1px 0;
  border-radius: 5px 5px 0px 0px;
}
</style>
